#!/usr/bin/env python
# coding=utf-8
"""
登录控制
"""
from flask import render_template, Blueprint, jsonify, session

from mynest.base.tools.jobsenum import Jobs
from mynest.pojo.logpojo import LogPojo
from mynest.service.logsv import LogSV
from mynest.service.usersv import UserSV

nestlogin = Blueprint('login', __name__)


@nestlogin.route('/')
def index():
    if 'token' in session:
        return render_template('index.html')
    else:
        return render_template('login/login.html')


@nestlogin.route('/login/<account>/<password>', methods=['GET'])
def login(account=None, password=None):
    """
    登录
    :param account: 账户
    :param password: 密码
    :return:
    """
    # token = request.cookies.get('token')
    if 'token' not in session:
        userSV = UserSV()
        flag = userSV.checkUser(account, password)
        if flag:
            # response = make_response(render_template('index.html'))
            # outdate = datetime.datetime.today() + datetime.timedelta(hours=1)
            # response.set_cookie('token', account, expires=outdate)
            session['token'] = account

            LogSV().addLog(LogPojo(job=Jobs.Login, log=str(account) + "登陆My Nest", account=account))
            return jsonify({"code": "00000", "success": True, "info": "登录成功", "url": "mynest"})
        else:
            return jsonify({"code": "10000", "success": False, "info": "登录失败"})
    else:
        return jsonify({"code": "00000", "success": True, "info": "登录成功", "url": "mynest"})


@nestlogin.route('/login/out')
def logout():
    if 'token' in session:
        session.pop('token')
    return jsonify({"code": "00000", "success": True, "info": "退出成功", "url": "login"})
